<template>
  <table-layout :haveSider="false" :isStandTable="false">
    <template #headCustom>
      <a-button type="primary" @click="onBack">返回</a-button>
      <a-button type="primary" style="marginLeft:20px" @click="onSure">确认</a-button>
      <!-- <a-button type="primary" style="marginLeft:20px" @click="onReset">重置</a-button> -->
    </template>
    <template #form>
        <div class="card">
            <div class="viewTitle">
            {{btn[0].name}}
            <a-button type="link" class="upAndDown"  @click="upAndDown($event,0)" >
                <a-icon v-if="btn[0].isUp" type="up"/>
                <a-icon v-else type="down"/>
            </a-button>
            </div>
            <basic-form
                v-show="btn[0].isUp"
                v-if="isExit"
                style="marginTop:50px"
                ref="form"
                :isBtn="false"
                :isInline="true"
                :formInfos="s_FormInfo"
                :formDatas="s_formDatas"
                :rules="s_rules"
                @onSubmit="onSubmit"
                @onChangeType="onChangeType"
            ></basic-form>
        </div>
        <div class="dis"></div>
        <div class="card">
            <div class="viewTitle">
            {{btn[1].name}}
            <a-button type="link" class="upAndDown" @click="upAndDown($event,1)" >
                <a-icon v-if="btn[1].isUp" type="up" />
                <a-icon v-else type="down" />
            </a-button>
            </div>
            <a-list-table
                v-show="btn[1].isUp"
                style="marginTop:5px"
                tableId="invoicesTable1"
                :columns="columns"
                :tableData="listdata"
                :isSelecttion="true"
                :loading="loading"
                :scroll="{y:null}"
                @onTableChange="handleTableChange"
                @onselectChange="onselectChange"
                >
                </a-list-table>
        </div>
    </template>
  </table-layout>
</template>

<script>
import tableLayout from '@/views/app/biz/common/index'
import basicForm from '../common/basicForm'
import aListTable from '@/views/app/biz/common/aListTable'
import {
  getInfoByPid,
  newInvoice
} from './invoice.js'
import {getStlDetailBydelOrder,getStlDetailByStlOrder} from '../settlement/settlement'
import storage from 'store'
import {
  s_FormInfo,
  s_formDatas,
  s_rules,
  productColomns
} from './dataConfig'
export default {
  components: {
    tableLayout,
    basicForm,
    aListTable
  },
  data() {
    return {
      btn: [
        { name: '发票信息', isUp: true },
        { name: '选择开票产品', isUp: true },
      ],
      isExit:true,
      orderType:null,
      order:[],
      selectedRowKeys:[],
      selectedRows:[],
      loading: false,
      s_FormInfo: s_FormInfo,
      s_formDatas: s_formDatas,
      s_rules: s_rules,
      columns:productColomns,
      listdata:[],
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 100000, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      backPathName:'invoice'
      
    }
  },
  computed: {},
  mounted(){
    //刷新页面时读取缓存
    if (!this.$route.params.type) {
      this.backPathName = storage.get('pathNameToI')? storage.get('pathNameToI') : this.backPathName
      this.orderType = storage.get('orderTypeToI')? storage.get('orderTypeToI'):null //订单类型：货票同行和用后结算
      this.order = storage.get('orderToI')? storage.get('orderToI'):[]  //已选订单数组
      if (storage.get('typeToI')=='edit') {
        this.editModal(this.$route.params.pid)
      }
      if (storage.get('typeToI')=='add') {
        this.addModal() 
      }
    }
  },
  activated(){
    console.log('activated',this.$route );
    //如果传了type值表示为重新点击进去的，需要初始化数据，如果未传值表示缓存在页签中，需路由配置keepAlive
    if (this.$route.params.type) {
        this.initData()
        this.backPathName = this.$route.params.pathName ? this.$route.params.pathName : this.backPathName
        this.orderType=this.$route.params.orderType
        this.order=this.$route.params.order
        storage.set('typeToI',this.$route.params.type)
        storage.set('pathNameToI',this.backPathName)
        storage.set('orderTypeToI',this.orderType)
        storage.set('orderToI',this.order)
        if (this.$route.params.type=='edit') {
          this.editModal(this.$route.params.pid)
        }
        if(this.$route.params.type=='add'){ 
          this.addModal() 
        }
    }
  },
  methods: {
    upAndDown (e, num) {
      if (this.btn[num].isUp) {
        this.btn[num].isUp = false
      } else {
        this.btn[num].isUp = true
      }
    },
    onBack() {
      this.$router.push({
        name: this.backPathName,
        params: {
          isJump: false,
          pathName: this.$route.name,
          iscloseMul:true,
        }
      })
    },
    initData(){
      console.log('重置数据');
      Object.assign(this.$data, this.$options.data.call(this))
      this.isExit=false
      setTimeout(()=>{
        this.isExit=true
      },1)
    },
    // 新增按钮 点击了新增
    addModal() {
      console.log('点击了新增')
      for (let item of this.s_FormInfo) {
        item.isDisabled = false
      }
      this.setParams()
    },
    // 新增按钮 点击了新增
    editModal(val) {
      console.log('点击了编辑')
      for (let item of this.s_FormInfo) {
        if (item.name === 'settlementPid') {
          item.isDisabled = true
        } else {
          item.isDisabled = false
        }
      }
      this.s_FormInfo=[...this.s_FormInfo]
      console.log(s_FormInfo);
      this.getSBypid(val)
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList()
    },
    setParams(){
      
      if (this.orderType=='delivery') {
        let pa={deliveryOrderNos:''}
        for (let item of this.order) {
          pa.deliveryOrderNos+=item.deliveryOrderNo+ ','
        }
        this.getList(pa)
      }else if(this.orderType=='settlement'){
        let pa={settlementNos:''}
        for (let item of this.order) {
          pa.settlementNos+=item.settlementNo+ ','
        }
        this.getList(pa)
      }
      
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn=[]
      let listdata=[]
      this.loading = true 
      let res = ''
      if (this.orderType=='delivery') {
        res = await getStlDetailBydelOrder(params, this.pagination)
      }else if (this.orderType=='settlement') {
        res = await getStlDetailByStlOrder(params, this.pagination)
      }
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            listdata.push({
               key: item.pid,
               action:actionBtn ,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys=selectedRowKeys
      this.selectedRows=selectedRows
      this.setPrice()
    },
    setPrice(){
      //含税总价
      let totalPrice=null
      //无税总价
      let totalIunitprice=null
      //税额
      let taxes=null
      //税率
      let tax=parseFloat(this.s_formDatas.tax)
      for (let item of this.selectedRows) {
        totalPrice+=item.totalPrice
      }
      taxes=(totalPrice*tax)/100
      totalIunitprice=totalPrice-taxes

      taxes = Math.round(taxes * 100) / 100
      totalIunitprice = Math.round(totalIunitprice * 100) / 100
      
      // taxes=taxes.toFixed(2)
      // totalIunitprice=totalIunitprice.toFixed(2)
      this.s_formDatas=this.$refs.form.form
      let s_formDatas={...this.s_formDatas}
      s_formDatas.totalPrice=totalPrice?totalPrice:null
      s_formDatas.taxes=taxes?taxes:null
      s_formDatas.totalIunitprice=totalIunitprice?totalIunitprice:null

      this.s_formDatas = s_formDatas
      
    },
    onReset(){
      this.$refs.form.resetForm()
    },
    onSure() {
      this.$refs.form.submitForm()
    },
    // 模态详细框提交按钮
    onSubmit(val) {
      if (!this.selectedRows.length) {
        this.$message.warning({content:'请先选择开票产品再提交信息！'})
        return
      }
      val.invoiceDetails=this.selectedRows
      this.saveObjInfo(val)
    },
    // 保存详细信息
    async saveObjInfo(val) {
      this.loading = true
      // this.$message.loading({ content: '提交中'， })
      console.log(val);
      let res = await newInvoice(val)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '提交成功',  duration: 2 })
        this.onBack()
      } else {
        this.$message.error({ content: '提交失败',  duration: 2 })
      }
    },
    // 得到初始化信息
    async getSBypid(val) {
      let res = await getInfoByPid(val)
      if (res && res.code && res.code === 'C1') {
        if (res.data) {
          res.data.tax+=''
          this.s_formDatas = {...this.s_formDatas, ...res.data}
          console.log(s_formDatas);
        } else {
          this.addModal()
        }
      }
      console.log(res)
    },

    // 表单编号
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      this.s_formDatas=this.$refs.form.form
      switch (name) {
        case 'settlementPid': 
          this.setDetail(val[1])
        break
        case 'customerName':
          let s_formDatas1={...this.s_formDatas}
          if (val[0]) { 
            s_formDatas1.customerName=val[1].orgName
            s_formDatas1.customerTaxNo=val[1].orgCode
            s_formDatas1.customerAddrTell=val[1].addTel
            s_formDatas1.customerAccountNum=val[1].invoiceHeadInfo
          }else{
            s_formDatas1.customerName=null
            s_formDatas1.customerTaxNo=null
            s_formDatas1.customerAddrTell=null
            s_formDatas1.customerAccountNum=null
          }
          this.s_formDatas=s_formDatas1
        break
        case 'supplierOrgName':
          let s_formDatas2={...this.s_formDatas}
          if (val[0]) { 
            s_formDatas2.supplierOrgName=val[1].orgName
            s_formDatas2.supplierTaxNo=val[1].orgCode
            s_formDatas2.supplierAddrTel=val[1].addTel
            s_formDatas2.supplierAccountNum=val[1].invoiceHeadInfo
          }else{
            s_formDatas2.supplierOrgName=null
            s_formDatas2.supplierTaxNo=null
            s_formDatas2.supplierAddrTel=null
            s_formDatas2.supplierAccountNum=null
          }
          this.s_formDatas=s_formDatas2
        break
        case 'tax':
          this.setPrice()
        break
      }
    },
    // 动态设置详细信息
    setDetail (res) {
      console.log(res);
      let changeVal={
        customerOrgPid: res.orgPid,
        settlementPid: res.pid,
        settlementNo: res.settlementNo,
        tax:res.tax+'',
        taxes:res.taxes,
        totalIunitprice:res.totalIunitprice,
        totalPrice:res.totalPrice
      }
      this.s_formDatas = {...this.s_formDatas,...changeVal}
    },
    //
    restData (val) {
       this.getSBypid(this.s_formDatas.pid)
    }
  },
}
</script>

<style>
.viewTitle {
  line-height: 30px;
  font-size: 16px;
  font-weight: bolder;
  color: #555;
  border-bottom: 1px solid #ccc;
  margin: 10px 0;
}
.upAndDown {
  text-align: center;
}
.card {
  width: 100%;
  padding: 0 7px;
}
.dis {
  height: 15px;
  background-color: #f0f2f5;
}
</style>